package com.um.pasantiaum.empresa.pedidos;

import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.parse.FindCallback;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseUser;
import com.parse.SaveCallback;
import com.um.pasantiaum.R;
import com.um.pasantiaum.objetos.Camion;
import com.um.pasantiaum.objetos.Pedido;
import com.um.pasantiaum.objetos.SelectedPedido;

public class SelectTruckFragment extends ListFragment {

	private ArrayList<Camion> mCamiones;
	private Pedido selectedOrder;
	private ArrayList<ParseObject> mCamionesParse;
	private Camion p;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		selectedOrder = SelectedPedido.getSelectedPedido().getPedido();

		mCamiones = new ArrayList<Camion>();
		mCamionesParse = new ArrayList<ParseObject>();

		ParseQuery<ParseObject> query = ParseQuery.getQuery("Truck");
		query.whereEqualTo("empresa", ParseUser.getCurrentUser());
		query.whereEqualTo("isInStock", true);
		query.include("truck");

		query.findInBackground(new FindCallback<ParseObject>() {

			@Override
			public void done(List<ParseObject> objects, ParseException e) {
				if (e != null) {
					Toast.makeText(getActivity().getApplicationContext(),
							e.getMessage(), Toast.LENGTH_LONG).show();
				} else {
					for (ParseObject po : objects) {
						ParseUser temp = po.getParseUser("truck");
						mCamiones.add(new Camion(temp));
						mCamionesParse.add(po);
					}

					AdminCamionesAdapter adapter = new AdminCamionesAdapter(
							mCamiones);
					setListAdapter(adapter);
				}

			}
		});

	}

	public class AdminCamionesAdapter extends ArrayAdapter<Camion> {

		public AdminCamionesAdapter(ArrayList<Camion> camion) {
			super(getActivity(), 0, camion);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = getActivity().getLayoutInflater().inflate(
						R.layout.list_item_product, null);
			}

			Camion p = getItem(position);
			TextView nameView = (TextView) convertView
					.findViewById(com.um.pasantiaum.R.id.prodruct_name);
			nameView.setText(p.getName());
			TextView descriptionView = (TextView) convertView
					.findViewById(com.um.pasantiaum.R.id.prodruct_description);
			descriptionView.setText(p.getEmail());
			TextView priceView = (TextView) convertView
					.findViewById(com.um.pasantiaum.R.id.product_price);
			priceView.setText("");

			return convertView;
		}
	}

	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {

		p = (Camion) ((AdminCamionesAdapter) getListAdapter())
				.getItem(position);

		AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
				getActivity());
		// set title
		alertDialogBuilder.setTitle("Asignar camion");

		// set dialog message
		alertDialogBuilder
				.setMessage(
						"Esta seguro que desea asignar a " + p.getName()
								+ " como el camion?")
				.setCancelable(false)
				.setPositiveButton("Aceptar",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								// if this button is clicked, close
								// current activity
								final ProgressDialog dlg = new ProgressDialog(
										getActivity());
								dlg.setTitle("Por favor espere");
								dlg.setMessage("Actualizando");
								dlg.show();
								ParseObject temp = null;

								for (ParseObject pu : mCamionesParse) {
									if (pu.getParseObject("truck")
											.getObjectId()
											.equalsIgnoreCase(p.getUserId()))
										temp = pu;
								}

								selectedOrder.getPedidoEnParse().put("truck",
										temp);
								selectedOrder.getPedidoEnParse().put("estado",
										"onRoute");
								selectedOrder.getPedidoEnParse()
										.saveInBackground(new SaveCallback() {

											@Override
											public void done(ParseException e) {
												dlg.dismiss();

												if (e != null) {

												} else {

													Intent i = new Intent(
															getActivity(),
															OpenPedidosEmpresaActivity.class);
													i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
													startActivity(i);

												}

											}
										});

							}
						})
				.setNegativeButton("Cancelar",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								// if this button is clicked, just close
								// the dialog box and do nothing
								dialog.cancel();
							}
						});

		// create alert dialog
		AlertDialog alertDialog = alertDialogBuilder.create();

		// show it
		alertDialog.show();

	}

}
